//
//  RouteViewController.m
//  Cycling
//
//  Created by 迟国强 on 2023/4/5.
//

#import "RouteViewController.h"
#import "RouteListCell.h"
#import "EditRouteController.h"
#import "RouteDetaliController.h"
#import "RouteRequest.h"
#import "MapRequest.h"
#import "YBPopupMenu.h"
#import <CoreLocation/CoreLocation.h>
#import "NotDataCell.h"
#import <Social/Social.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>

#import <FBSDKShareKit/FBSDKShareKit.h>

#import "PerfectMessageViewController.h"
#import "Cycling-Swift.h"

@interface RouteViewController ()<UITableViewDelegate, UITableViewDataSource,YBPopupMenuDelegate,UITextFieldDelegate,CLLocationManagerDelegate>

@property (nonatomic, strong) NSMutableArray *dataArray;  // 列表数据
@property (nonatomic, strong) UIButton *screenBtn;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UITextField *searchTF;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) NSString *key;
@property (nonatomic, strong) NSString *type;
@property (nonatomic, strong) UIView *naviBarView;
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, retain) CLLocation *myLocation;
@property (nonatomic, assign) NSInteger index;

@property (nonatomic) BOOL dataIsLoading;

@end

@implementation RouteViewController

- (UIView *)naviBarView {
    if (!_naviBarView) {
        _naviBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, NavigationBarHeight)];
        _naviBarView.backgroundColor = COLOR_WHITE;
        UILabel *titleLB = [[UILabel alloc] initWithFrame:CGRectMake(MARGIN_MAX, SafeAreaTopHeight, SCREEN_W-MARGIN_MAX*2, 44)];
        titleLB.text = CycLocalizedString(@"Routes", @"路线");
        titleLB.textAlignment = NSTextAlignmentCenter;
        titleLB.textColor = rgbHex(0x222222, 1.0);
        titleLB.font = FONT_PRIMARY_TITLE;
        [_naviBarView addSubview:titleLB];
    }
    return _naviBarView;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self startLocation];

}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = rgbHex(0xF8F8F8, 1);
    self.page = 1;
    self.key = @"";
    self.type = @"";
    
    [self.view addSubview:self.naviBarView];
    [self.view addSubview:self.tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.top.equalTo(self.view).offset(NavigationBarHeight);
        make.bottom.equalTo(self.view).offset(-60-SafeAreaBottomHeight);
    }];

    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 1;
        [self loadDataWithShowLoadview:NO];
    }];
    header.loadingView.color = rgb(70, 221, 162);
    self.tableView.mj_header = header;
    
    MJRefreshBackFooter *footer = [MJRefreshBackFooter footerWithRefreshingBlock:^{
        self.page ++;
        [self loadDataWithShowLoadview:NO];
    }];
    self.tableView.mj_footer = footer;

}

- (void)loadData
{
    [self loadDataWithShowLoadview:YES];
}

- (void)loadDataWithShowLoadview:(BOOL)showLoadingView {
    if(self.myLocation == nil){
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        self.dataIsLoading = NO;
        [self.tableView reloadData];
        return;
    }
    self.key = self.searchTF.text;
    if(showLoadingView) {
        [self showLoadingViewWithText:nil];
    }
    self.dataIsLoading = YES;
    [self.tableView reloadData];
    [RouteRequest getRouteListWithPage:self.page pageSize:50 key:self.key type:self.type lat:[NSString stringWithFormat:@"%f",self.myLocation.coordinate.latitude] lng:[NSString stringWithFormat:@"%f",self.myLocation.coordinate.longitude] result:^(RouteListModel * _Nonnull list) {
        [self removeLoadingView];
        if (list != nil) {
            if (self.page == 1) {
                [self.dataArray removeAllObjects];
                [self.dataArray addObjectsFromArray:list.list];
            } else {
                [self.dataArray addObjectsFromArray:list.list];
            }
        }
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        self.dataIsLoading = NO;
        [self.tableView reloadData];
    }];
}

//开始定位
- (void)startLocation {
    //初始化定位管理者
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;

    //判断设备是否能够进行定位
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if ([CLLocationManager locationServicesEnabled]) {
            //精确度获取到米
            self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
            //设置过滤器为无
            self.locationManager.distanceFilter = kCLDistanceFilterNone;
            // 取得定位权限，有两个方法，取决于你的定位使用情况
            //一个是requestAlwaysAuthorization，一个是requestWhenInUseAuthorization
            [self.locationManager requestWhenInUseAuthorization];
            //开始获取定位
            [self.locationManager startUpdatingLocation];
            //地理信息
    //        self.geoCoder = [[CLGeocoder alloc] init];
        } else {
            DebugLog(@"error");
        }
    });
}

//设置获取位置信息的代理方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    NSLog(@"%lu", (unsigned long)locations.count);
    self.myLocation = locations.lastObject;
    DebugLog(@"经度：%f 纬度：%f", _myLocation.coordinate.longitude, _myLocation.coordinate.latitude);
    
    //不用的时候关闭更新位置服务，不关闭的话这个 delegate 隔一定的时间间隔就会有回调
    [self.locationManager stopUpdatingLocation];
    [self loadData];
    
}
//问题函数
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if (error) {
        [self loadData];

        DebugLog(@"error:%ld", (long)error.code);
    }
}

// 分享
- (void)shareAction {
//    FBSDKShareLinkContent *linkContent = [[FBSDKShareLinkContent alloc]init];
//    linkContent.contentURL= [NSURL URLWithString:@"分享链接"];
//    linkContent.quote = @"描述信息";
//

//    [FBSDKShareDialog dialogWithViewController:self withContent:<#(id<FBSDKSharingContent> _Nullable)#> delegate:<#(id<FBSDKSharingDelegate> _Nullable)#>]
//    FBSDKShareDialog *shareDialog = [[FBSDKShareDialog alloc]init];
//    // 需要指定模式，否则会调起web分享
//    shareDialog.mode = FBSDKShareDialogModeNative;
//    if (![shareDialog canShow]) {
//        shareDialog.mode = FBSDKShareDialogModeWeb;
//    }
//    shareDialog.shareContent = linkContent;
//    shareDialog.delegate = self;
//    shareDialog.fromViewController = self;
//    [shareDialog show];
    
    //分享实现博客
    // https://www.jianshu.com/p/4fa469f5fe27
    
//    NSURL *url = [NSURL fileURLWithPath:@""];
//    NSString *str = @"分享路线";
//    NSArray *activityItems = @[str];
//    UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
//    activityVC.excludedActivityTypes = @[UIActivityTypeAddToReadingList];
//    [self presentViewController:activityVC animated:YES completion:nil];
//    // 分享之后的回调
//    activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
//        if (completed) {
//            NSLog(@"-----分享 成功");
//        } else  {
//            NSLog(@"-----分享 取消");
//        }
//    };
}


#pragma mark - tableView delegate datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(self.dataArray.count == 0 && self.dataIsLoading) {
        return 0;
    }
    return self.dataArray.count == 0 ? 1 : self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(self.dataArray.count == 0){
        NotDataCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NotDataCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if ([CLLocationManager locationServicesEnabled] && ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized)) {
        //定位功能可用
            cell.titleL.text = CycLocalizedString(@"No routes", @"暂无数据");
        }else if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) {
        //定位不能用
            cell.titleL.text = CycLocalizedString(@"The device location permission is not enabled. Please set the location permission in the settings", @"未开启设备位置权限,请到设置里设置位置权限");
        }
        return cell;
    }
    RouteListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RouteListCell"];
    cell.model = self.dataArray[indexPath.row];
    cell.goodBlock = ^(RouteDetailModel * _Nonnull model) {
        tableView.userInteractionEnabled = NO;
        if (model.ispraise) {
            [RouteRequest cancelPraiseRouteWithRouteId:model.id result:^(NSDictionary * _Nonnull ret) {
                tableView.userInteractionEnabled = YES;
                if(!ret) {
                    return;
                }
                model.ispraise = NO;
                model.praisenum = [NSString stringWithFormat:@"%d", model.praisenum.intValue - 1];
                [self.tableView reloadData];
            }];
        } else {
            [RouteRequest praiseRouteWithRouteId:model.id result:^(NSDictionary * _Nonnull ret) {
                tableView.userInteractionEnabled = YES;
                if(!ret) {
                    return;
                }
                model.ispraise = YES;
                model.praisenum = [NSString stringWithFormat:@"%d", model.praisenum.intValue + 1];
                [self.tableView reloadData];
            }];
        }
    };
    cell.collectionBlock = ^(RouteDetailModel * _Nonnull model) {
        tableView.userInteractionEnabled = NO;
        if (model.iscollection) {
            [RouteRequest cancleCollectionRouteWithRouteId:model.id result:^(NSDictionary * _Nonnull ret) {
                tableView.userInteractionEnabled = YES;
                if(!ret) {
                    return;
                }
                model.iscollection = NO;
                model.collectionnum = [NSString stringWithFormat:@"%d", model.collectionnum.intValue - 1];
                [self.tableView reloadData];
            }];
        } else {
            [RouteRequest collectionRouteWithRouteId:model.id result:^(NSDictionary * _Nonnull ret) {
                tableView.userInteractionEnabled = YES;
                if(!ret) {
                    return;
                }
                model.iscollection = YES;
                model.collectionnum = [NSString stringWithFormat:@"%d", model.collectionnum.intValue + 1];
                [self.tableView reloadData];
            }];
        }
    };
    cell.shareBlock = ^(RouteDetailModel * _Nonnull model) {
//        [self shareAction];
        NSString *shareImageString = model.lineimg;
        if(model.fulllineimg.length > 0) {
            shareImageString = model.fulllineimg;
        }
        NSMutableArray *sharedImageNames = [NSMutableArray array];
        if(shareImageString) {
            [sharedImageNames addObject:shareImageString];
        }
        if(model.fullimgs.count > 0) {
            [sharedImageNames addObjectsFromArray:model.fullimgs];
        } else if(model.imgs.count > 0) {
            [sharedImageNames addObjectsFromArray:model.imgs];
        }
//        [self showLoadingViewWithText:@""];
        [CSFacebookShareManager sharedWithImageStrings:sharedImageNames fromViewController:self complete:^(BOOL success, BOOL cancel) {
            [self removeLoadingView];
            if(!success && !cancel) {
                [self showHudTipStr: CycLocalizedString(@"Shared fail", @"分享失败")];
            }
        }];
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return self.dataArray.count == 0 ? self.tableView.bounds.size.height - 60 : UITableViewAutomaticDimension;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(self.dataArray.count == 0){
        
        NSURL *url = [[NSURL alloc] initWithString:UIApplicationOpenSettingsURLString];

        [[UIApplication sharedApplication] openURL:url options:nil completionHandler:^(BOOL success) {

        }];
        return;
    }
    RouteDetaliController *vc = [[RouteDetaliController alloc] init];
    vc.model = self.dataArray[indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = rgbHex(0xF8F8F8, 1);
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        } else {
            // Fallback on earlier versions
        }

        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"RouteListCell" bundle:nil] forCellReuseIdentifier:@"RouteListCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"NotDataCell" bundle:nil] forCellReuseIdentifier:@"NotDataCell"];

        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 60)];
        UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(20, 10, SCREEN_W-100, 40)];
        whiteView.backgroundColor = [UIColor whiteColor];
        [whiteView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)]];
        whiteView.layer.cornerRadius = 20;
        [headerView addSubview:whiteView];

        UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(25, 20, 20, 20)];
        iv.image = [UIImage imageNamed:@"sousuo"];
        [headerView addSubview:iv];
        
        self.searchTF = [[UITextField alloc] initWithFrame:CGRectMake(50, 15, whiteView.ce_width - 50, 30)];
        _searchTF.placeholder = CycLocalizedString(@"Search route", @"搜索路线");
        _searchTF.textColor = rgb(176, 176, 176);
        _searchTF.keyboardType = UIKeyboardTypeDefault;
        _searchTF.clearButtonMode = UITextFieldViewModeWhileEditing;
        _searchTF.borderStyle = UITextBorderStyleNone;
        _searchTF.font = [UIFont systemFontOfSize:16];
        _searchTF.delegate = self;
        [headerView addSubview:_searchTF];
        
        UIButton *myRouteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [myRouteBtn setImage:[UIImage imageNamed:@"searchim"] forState:UIControlStateNormal];
        myRouteBtn.frame = CGRectMake(SCREEN_W - 50, 17, 26, 26);
        [headerView addSubview:myRouteBtn];
        [myRouteBtn addTarget:self action:@selector(screenAction) forControlEvents:(UIControlEventTouchUpInside)];
        self.screenBtn = myRouteBtn;
        _tableView.tableHeaderView = headerView;
    }
    return _tableView;
}

- (void)tap {

}

- (void)screenAction {
    NSArray *titles = @[CycLocalizedString(@"All", @"全部"), CycLocalizedString(@"Have Saved", @"我的收藏"), CycLocalizedString(@"My Private Routes", @"我的私人路线"), CycLocalizedString(@"RouteVC-MyRoutes", @"我的路线")];
    NSArray *imageArr = @[[UIImage imageNamed:@"route_all"],[UIImage imageNamed:@"collect"],[UIImage imageNamed:@"myrouteim"],[UIImage imageNamed:@"route_myroute_icon"]];
    [YBPopupMenu showRelyOnView:self.screenBtn index:self.index titles:titles icons:imageArr menuWidth:200 backColor:rgba(0, 0, 0, 0.8) textColor:COLOR_WHITE font:PingFangFont(20) delegate:self];
}

#pragma mark - YBPopupMenuDelegate
- (void)ybPopupMenu:(YBPopupMenu *)ybPopupMenu didSelectedAtIndex:(NSInteger)index {
    
    NSLog(@"点击了 %@ 选项",@(index));
    if (index == 0) {
        self.type = @"";
    } else if(index == 3) {
        self.type = @"my";
    } else {
        self.type = index == 1 ? @"collection" : @"private";
    }
    self.index = index;
    [self.tableView.mj_header beginRefreshing];
    [self loadDataWithShowLoadview:NO];
}

#pragma MARK: UITextFieldDelegate
-(void)textFieldEditingChange{
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    [self loadData];
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    return YES;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.view endEditing:YES];
    
    self.key = textField.text;
    [self loadData];

    return YES;
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    return YES;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

@end
